const crypto = require('crypto');

class CrypUtil {

    constructor(){}

    /**
     * aes加密
     * @param data 待加密的字符串
     * @param key 加密用的key
     */
    aesEncrypt(data, key, isUser=false){
        data = new Buffer(data).toString('base64');
        // console.log(data);
        let clearEncoding = 'utf8';
        let cipherEncoding = 'base64';
        let cipherChunks = [];
        if(isUser){
            key = key + "aes-256-ecb01"
        }
        let cipher = crypto.createCipheriv('aes-256-ecb', key, "");
        cipher.setAutoPadding(true);
        cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
        cipherChunks.push(cipher.final(cipherEncoding));
        return cipherChunks.join('');
    }

    aesDecrypt(data, key, isUser=false){
        if (!data) {
            return "";
        }
        let clearEncoding = 'utf8';
        let cipherEncoding = 'base64';
        let cipherChunks = [];
        if(isUser){
            key = key + "aes-256-ecb01"
        }
        let decipher = crypto.createDecipheriv('aes-256-ecb', key, "");
        decipher.setAutoPadding(true);
        cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
        cipherChunks.push(decipher.final(clearEncoding));
        return cipherChunks.join('');
    }
}

let crypUtil = new CrypUtil();
module.exports = crypUtil
